﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Pahan.McuFusion.Common;

namespace Pahan.McuFusion.Files
{
    public class BinaryFileWriter : IFileWriter
    {
        public BinaryFileWriter(Stream stream)
        {
            Assert.NotNull(stream, "stream");
            if (!stream.CanWrite)
            {
                throw new ArgumentException("The stream cannot be written to.", "stream");
            }
            if (!stream.CanSeek)
            {
                throw new ArgumentException("The stream cannot be seeked.", "stream");
            }

            this.stream = stream;
        }
        
        #region Implementation of IDisposable

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        /// <filterpriority>2</filterpriority>
        public void Dispose()
        {
            stream.Close();
        }

        #endregion

        #region Implementation of IFileWriter

        /// <summary>
        /// Gets the default value. This value may be skiped while writing,
        /// if the output format supports such behavior.
        /// </summary>
        public byte DefaultValue
        {
            get; set;
        }

        /// <summary>
        /// Writes the data to the file.
        /// </summary>
        public void WriteAll(IList<byte> data)
        {
            const int maxBlockSize = 4096;
            for (int dataIndex = 0; dataIndex < data.Count; dataIndex += maxBlockSize)
            {
                int blockSize = Math.Min(maxBlockSize, data.Count - dataIndex);
                byte[] buf = new byte[blockSize];
                for (int i = 0; i < blockSize; i++)
                {
                    buf[i] = data[dataIndex + i];
                }
                stream.Write(buf, 0, buf.Length);
            }
        }

        #endregion

        #region Private Members

        private readonly Stream stream;

        #endregion
    }
}
